%{
#include<stdio.h>
#include"y.tab.h"

  
  void print_begin() {
        puts("@str = constant [ 7 x i8 ] c\"=> %d\\0A\\00\"");
        puts("declare i32 @printf(i8*, ...)\n");
        puts("define i32 @calcule() {");
}

void print_end() {
        puts("}\n");
        puts("define i32 @main() {");
        puts("\t%x = call i32 @calcule()");
        puts("\tcall i32 (i8*, ...)* @printf(i8* getelementptr ([7 x i8]* @str, i32 0, i32 0), i32 %x)");
        puts("\tret i32 0\n}");
}

 int compt = 0; 
  
    
  
%}

//definit le type de yylval
%union{
  int i;
  char *s;
 }
%token <s> ID
%token <i>  N
%type <i> E
%type <i> F
%type <i> T

%%
S
: I S
| I              
;
I
: ID '=' E ';'   { printf("%%%s = alloca i32\n", $1); printf("store i32 %%t%d, i32* %%%s\n",$3, $1); }
;
E
: T '+' E        { printf("%%t%d = add i32 %%t%d, %%t%d\n", compt, $1, $3); $$ = compt; compt++;}
| T '-' E        { printf("%%t%d = sub i32 %%t%d, %%t%d\n", compt, $1, $3); $$ = compt; compt++;}
| T              { $$ = $1;}
;
T                
: F '*' T        { printf("%%t%d = mul i32 %%t%d, %%t%d\n", compt, $1, $3);  $$ = compt; compt++;}
| F              { $$ = $1;}
;
F
: N              { printf("%%t%d = add i32 %d,0\n",compt, $1);    $$ = compt; compt++;}
| ID             { printf("%%t%d = load i32* %%%s\n",compt, $1);    $$ = compt; compt++;}
| '(' E ')'      { $$ = $2;}
;
%%
int main(int argc, char **argv) {
 
        print_begin();
        yyparse();
        print_end();
        return 0;
}
